package com.swotxu.mall.ssoserver.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Date: 2021/3/16 21:11
 * @Author: swotXu
 */
@Slf4j
@Controller
public class LoginController {
    public static final String SSO_TOKEN = "sso_token";

    @Autowired
    StringRedisTemplate redisTemplate;

    @ResponseBody
    @GetMapping("/userInfo")
    public String loginPage(@RequestParam("token") String token) {
        return redisTemplate.opsForValue().get(token);
    }

    @GetMapping("/login.html")
    public String loginPage(@RequestParam("redirect_url") String redirectUrl, Model model
            , @CookieValue(value = SSO_TOKEN, required = false) String ssoToken) {
        log.info("回调地址: {}, ssoToken: {}", redirectUrl, ssoToken);

        if (!StringUtils.isEmpty(ssoToken) && !StringUtils.isEmpty(redisTemplate.opsForValue().get(ssoToken))) {
            // 已有客户端登录过
            String url = redirectUrl + "?_token=" + ssoToken;
            log.info("已登录！url: {}", url);
            return "redirect:" + url;
        }

        model.addAttribute("redirectUrl", redirectUrl);
        return "login";
    }

    @PostMapping("/doLogin")
    public String doLogin(@RequestParam("username") String username, @RequestParam("password")String password
            , @RequestParam("redirectUrl")String redirectUrl, RedirectAttributes redirectAttributes, HttpServletResponse response) {
        log.info("用户名：{}, 密码：{}， 回调地址： {}", username, password, redirectUrl);
        if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password) || StringUtils.isEmpty(redirectUrl)) {
            log.warn("登陆失败！");
            return "login";
        }
        String token = UUID.randomUUID().toString().replace("-", "");
        // 1、将用户信息记录 Redis
        redisTemplate.opsForValue().set(token, username, 5, TimeUnit.MINUTES);
        // 2、将 Token 返回给浏览器
        Cookie cookie = new Cookie(SSO_TOKEN, token);
        response.addCookie(cookie);
        // redirectAttributes.addFlashAttribute("loginUser", username);
        // 登陆成功，跳回来源地址
        String url = redirectUrl + "?_token=" + token;
        log.info("登陆成功！url: {}", url);
        return "redirect:" + url;
    }

    @ResponseBody
    @GetMapping("/logout")
    public Boolean logout(@RequestParam("token") String token) {
        Boolean delete = redisTemplate.delete(token);
        log.info("用户[{}]退出[{}]!", token, delete);
        return delete;
    }
}
